﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RequestLocalization;
using Volo.Abp.AspNetCore.Mvc.Localization;
using Volo.Abp.Localization;
using Volo.Abp;

namespace Ebusiness_Host.Controllers
{
    /// <summary>
    /// 本地化语言切换接口
    /// </summary>
    [Route("Language/Switch")]
    [ApiController]
    public class LanguageSwitchController : ControllerBase
    {
        protected IQueryStringCultureReplacement QueryStringCultureReplacement { get; }

        public LanguageSwitchController(IQueryStringCultureReplacement queryStringCultureReplacement)
        {
            QueryStringCultureReplacement = queryStringCultureReplacement;
        }

        [HttpGet]
        public virtual async Task<string> Switch(string culture, string uiCulture = "")
        {
            if (!CultureHelper.IsValidCultureCode(culture))
            {
                throw new AbpException("Unknown language: " + culture + ". It must be a valid culture!");
            }

            // 1、语言存储到cookie中
            AbpRequestCultureCookieHelper.SetCultureCookie(
                HttpContext,
                new RequestCulture(culture, uiCulture)
            );

            HttpContext.Items[AbpRequestLocalizationMiddleware.HttpContextItemName] = true;

            var context = new QueryStringCultureReplacementContext(HttpContext, new RequestCulture(culture, uiCulture), "");
            await QueryStringCultureReplacement.ReplaceAsync(context);

            return "语言切换成功";
        }
    }
}
